package com.nbsaas.boot.shop.ext.resource;

import com.nbsaas.boot.rest.response.ListResponse;
import com.nbsaas.boot.shop.api.domain.simple.ShopCategorySimple;
import com.nbsaas.boot.shop.data.entity.ShopCategory;
import com.nbsaas.boot.shop.data.repository.ShopCategoryRepository;
import com.nbsaas.boot.shop.ext.apis.ShopCategoryExtApi;
import com.nbsaas.boot.shop.rest.convert.ShopCategorySimple2Convert;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service
public class ShopCategoryExtResource implements ShopCategoryExtApi {

    @Resource
    private ShopCategoryRepository shopCategoryRepository;

    @Transactional(readOnly = true)
    @Override
    public ListResponse<ShopCategorySimple> tree() {
        ListResponse<ShopCategorySimple> result = new ListResponse<>();

        List<ShopCategory> list = shopCategoryRepository.findAll();
        if (list != null) {
            List<ShopCategorySimple> simples = list.stream().map(new ShopCategorySimple2Convert()).collect(Collectors.toList());
            result.setData(convertToTree(simples));
        }
        return result;
    }

    public List<ShopCategorySimple> convertToTree(List<ShopCategorySimple> categoryList) {
        // 创建一个 Map 以便通过 id 快速查找节点
        Map<Long, ShopCategorySimple> categoryMap = new HashMap<>();
        for (ShopCategorySimple category : categoryList) {
            categoryMap.put(category.getId(), category);
        }

        // 创建根节点列表
        List<ShopCategorySimple> rootNodes = new ArrayList<>();
        for (ShopCategorySimple category : categoryList) {
            if (category.getParent() == null) {
                category.setParent(-1L);
            }
            // 如果当前节点的父节点为空，则将其添加到根节点列表中
            if (category.getParent() == 1L) {
                rootNodes.add(category);
            } else {
                // 否则将当前节点添加到父节点的子节点列表中
                ShopCategorySimple parent = categoryMap.get(category.getParent());
                if (parent != null) {
                    if (parent.getChildren() == null) {
                        parent.setChildren(new ArrayList<>());
                    }
                    parent.getChildren().add(category);
                }
            }
        }

        return rootNodes;
    }
}
